package com.rpc.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Description 编码器
 * @Author 顾志杰
 * @Date 2022/3/2 10:55
 */
public class RpcEncoder extends MessageToByteEncoder {

  private Class<?> genericClass;

  public RpcEncoder(Class<?> genericClass){
    this.genericClass = genericClass;
  }

  /**
   * 编码需要做的事情
   * 1.把对应的java对象进行编码
   * 2.之后把内容填充到buffer中去
   * 3.写出到Server端
   * @param ctx
   * @param msg
   * @param out
   * @throws Exception
   */
  @Override
  protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    if(genericClass.isInstance(msg)){
      byte[] data = Serialization.serialize(msg);
      /*消息分为 1.包头(数据包长度必然有4个字节) 2.包体(数据包内容)*/
      out.writeInt(data.length);
      out.writeBytes(data);
    }

  }
}
